import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:saas_order_meal/model/order_request_data.dart';
import 'package:saas_order_meal/net/net_response/elder_month_record.dart';
import 'package:saas_order_meal/net/net_response/order_detail_data.dart';
import 'package:saas_order_meal/saas_order_meal.dart';
import 'package:saas_order_meal/ui/by_week_food_menu.dart';
import 'package:saas_order_meal/ui/select_place_page.dart';
import 'package:saas_order_meal/ui/week_menu_choose_page.dart';
import 'package:saas_order_meal/utils/meal_ext_utils.dart';
import 'package:saas_order_meal/viewmodel/elder_month_record_view_model.dart';

import '../model/elder_info_data.dart';
import '../net/apis.dart';
import 'has_ordered_meal_page.dart';

class ElderMonthFoodPage extends BaseStatefulMvvmWidget {
  final String oldId;
  ElderInfoData? oldInfo;

  ElderMonthFoodPage(this.oldId, {this.oldInfo});

  @override
  State<StatefulWidget> createState() => _ElderMonthFoodState();
}

class _ElderMonthFoodState
    extends BaseMvvmListState<ElderMonthRecordViewModel, ElderMonthFoodPage> {
  @override
  Widget buildRootView(BuildContext context, Widget loadingContentWidget) {
    return Scaffold(
      appBar: AppBar(
        title: Text("点餐详情"),
      ),
      body: loadingContentWidget,
    );
  }

  @override
  Widget createItemWidget(int index) {
    var item = viewModel.listItems[index];
    var date = (item.date ?? "").replaceAll(" ", "\n");
    return Row(
      children: [
        CommonText('${date.formatDate(['yyyy', '/', 'mm', '/', 'dd'])}',
                height: 1.3, textAlign: TextAlign.center, textSize: 17)
            .setWeight(6),
        ((item.breakfast != null || item.breakfastSp != null)
                ? Icon(
                    Icons.check_circle,
                    color: Colors.green,
                  )
                : CommonText('点餐', textAlign: TextAlign.center, textSize: 15))
            // .onTap(() {
            // toOrderPage(date: item.date ?? "",meal:item);
            // })
            .setWeight(3),
        ((item.lunch != null || item.lunchSp != null)
                ? Icon(
                    Icons.check_circle,
                    color: Colors.green,
                  )
                : CommonText('点餐', textAlign: TextAlign.center, textSize: 15))
            // .onTap(() {
            // toOrderPage(meal:item, date: item.date ?? "");
            // })
            .setWeight(3),
        ((item.dinner != null || item.dinnerSp != null)
                ? Icon(
                    Icons.check_circle,
                    color: Colors.green,
                  )
                : CommonText('点餐', textAlign: TextAlign.center, textSize: 15))
            // .onTap(() {
            // toOrderPage(meal:item, date: item.date ?? "");
            // }
            // )
            .setWeight(3),
        (!item.allOrdered
                ? CommonText('去点餐',
                        textAlign: TextAlign.center,
                        textSize: 15,
                        textColor: SaasOrderMeal.mainColor)
                    .onTap(() {
                    // showCancelFoodSheet(context,
                    //     breakfastId: item.breakfast,
                    //     lunchId: item.lunch,
                    //     dinnerId: item.dinner,
                    //     date: item.date);
                    toOrderPage(meal: item, date: item.date ?? "");
                  })
                : Container())
            .setWeight(3),
      ],
    ).onTap(() async {
      // if(BuildConfig.isDebug){
      //   toOrderPage(meal:item, date: item.date ?? "");
      //   return;
      // }
      if (item.hasOrdered) {
        var list = <HasOrderData>[];
        if (item.breakfastOrderInfo != null) {
          list.add(HasOrderData(name: "早餐", detail: item.breakfastOrderInfo!));
        }
        if (item.lunchOrderInfo != null) {
          list.add(HasOrderData(name: "午餐", detail: item.lunchOrderInfo!));
        }
        if (item.dinnerOrderInfo != null) {
          list.add(HasOrderData(name: "晚餐", detail: item.dinnerOrderInfo!));
        }

        if (item.breakfastSpOrderInfo != null) {
          list.add(
              HasOrderData(name: "特色早", detail: item.breakfastSpOrderInfo!));
        }

        if (item.lunchSpOrderInfo != null) {
          list.add(HasOrderData(name: "特色午", detail: item.lunchSpOrderInfo!));
        }

        if (item.dinnerSpOrderInfo != null) {
          list.add(HasOrderData(name: "特色晚", detail: item.dinnerSpOrderInfo!));
        }
        var dateStr = item.date!.substring(0, 10);
        // Go().push(HasOrderedMealPage(hasOrderMealList: list,date: dateStr,));
        var data =
            await showDetail(context, hasOrderMealList: list, date: dateStr);
        if (data != null) {
          viewModel.requestRefresh();
        }
      } else {
        toOrderPage(meal: item, date: item.date ?? "");
      }
    }).addToContainer(
        color: index % 2 == 0 ? Colors.white : Colors.grey[100],
        padding: EdgeInsets.symmetric(vertical: 6));
  }

  @override
  Widget buildLoadingContentView() {
    var old = widget.oldInfo;
    return Column(
      children: [
        if (old != null)
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              widget.oldInfo?.imageHead == null
                  ? Image.asset(
                      "images/none.png",
                      package: "saas_order_meal",
                      width: 70,
                      height: 70,
                    )
                  : CachedNetworkImage(
                      imageUrl: "${Apis.imageHead}${widget.oldInfo?.imageHead}",
                      httpHeaders: ImageLoad.globalHeader,
                      width: 70,
                      height: 70,
                      placeholder: (context, url) {
                        return Image.asset(
                          "images/none.png",
                          package: "saas_order_meal",
                          width: 70,
                          height: 70,
                        );
                      },
                      errorWidget: (context, url, error) {
                        return Image.asset(
                          "images/none.png",
                          package: "saas_order_meal",
                          width: 70,
                          height: 70,
                        );
                      },
                    ),
              Container(
                width: 10,
              ),
              Column(
                children: [
                  Container(
                    height: 10,
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      CommonText('姓名：${old.name}', textSize: 14).setWeight(5),
                      CommonText('年龄：${old.age == null ? '——' : '${old.age}岁'}',
                              textSize: 14)
                          .setWeight(5),
                      CommonText('性别：${old.sex ?? "——"}', textSize: 14)
                          .setWeight(4),
                    ],
                  ),
                  Container(
                    height: 20,
                  ),
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      CommonText('床位号：${old.bedNo ?? '——'}', textSize: 14)
                          .setWeight(5),
                      CommonText(
                              '餐别：${viewModel.packageInfo.isNullOrEmpty() ? '——' : viewModel.packageInfo}',
                              textSize: 14)
                          .setWeight(5),
                      CommonText('', textSize: 14).setWeight(4),
                    ],
                  )
                ],
              ).setWeight(1)
            ],
          ).addToContainer(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10)),
        Row(
          children: [
            CommonText('日期', textAlign: TextAlign.center, textSize: 15)
                .setWeight(6),
            CommonText('早餐', textAlign: TextAlign.center, textSize: 15)
                .setWeight(3),
            CommonText('午餐', textAlign: TextAlign.center, textSize: 15)
                .setWeight(3),
            CommonText('晚餐', textAlign: TextAlign.center, textSize: 15)
                .setWeight(3),
            CommonText('').setWeight(3),
          ],
        ).addToContainer(
            color: Colors.grey[100],
            padding: EdgeInsets.symmetric(vertical: 6)),
        super.buildLoadingContentView()!.setWeight(1)
      ],
    );
  }

  @override
  ElderMonthRecordViewModel createViewModel() {
    return ElderMonthRecordViewModel(context, widget.oldId);
  }

  var inProcess = false;

  Future<void> toOrderPage(
      {required String date, required ElderMonthRecordList meal}) async {
    // var data = await getOrderType();
    // Go().push(SingleOrderSelectPlacePage(
    //   data.orderType.toString(),
    //   data.id.toString(),
    //   oldId: widget.oldId,
    //   mealId: mealId,
    // ));

    if (inProcess) {
      return;
    }
    inProcess = true;
    var hasOrderList = <int>[];
    if (meal.breakfast != null) {
      hasOrderList.add(1);
    }
    if (meal.lunch != null) {
      hasOrderList.add(2);
    }
    if (meal.dinner != null) {
      hasOrderList.add(3);
    }

    if (meal.breakfastSp != null) {
      hasOrderList.add(4);
    }
    if (meal.lunchSp != null) {
      hasOrderList.add(5);
    }
    if (meal.dinnerSp != null) {
      hasOrderList.add(6);
    }
    var dateStr = date.substring(0, 10);
    var data = await viewModel.getElderBindInfo(dateStr);
    if (data != null) {
      if (data.canSkipSelect == true) {
        var siteId = data.canUseSiteList!.first.siteId.toString();
        var siteName = data.canUseSiteList!.first.siteName ?? "";
        var useType = data.bindUseType;
        var orderData = OrderRequestData(
            siteId: siteId,
            siteName: siteName,
            elderName: widget.oldInfo?.name ?? "",
            date: dateStr,
            elderHumanId: widget.oldId,
            userRoomId: widget.oldInfo?.roomId,
            useType: useType,
            useTypeName: data.bindUseTypeName ?? "",
            timeSection: "");
        orderData.weekHasOrderedMeal ??= {};
        orderData.hasOrderedMeal = hasOrderList;
        toOrder(orderData);
      } else {
        var siteData = await showSelectSite(context,
            orderModelId: 4, siteList: data.canUseSiteList ?? []);
        if (siteData != null) {
          var orderData = OrderRequestData(
              elderName: widget.oldInfo?.name ?? "",
              siteId: siteData!['siteId'],
              siteName: siteData!['siteName'],
              date: dateStr,
              userRoomId: widget.oldInfo?.roomId,
              elderHumanId: widget.oldId,
              useType: siteData!['useType'],
              useTypeName: siteData['useTypeName'],
              timeSection: "");
          orderData.weekHasOrderedMeal ??= {};
          orderData.hasOrderedMeal = hasOrderList;
          toOrder(orderData);
        }
      }
    }
    inProcess = false;
  }

  Future<void> toOrder(OrderRequestData orderData) async {
    if (SaasOrderMeal.menuModel == MenuModel.BY_DAY) {
      var data = await Go().push(WeekMenuChoosePage(
        orderData: orderData,
      ));
      if (data != null) {
        viewModel.requestRefresh();
      }
    } else if (SaasOrderMeal.menuModel == MenuModel.BY_WEEK) {
      var date = DateTime.parse(orderData.date!);
      var week = date.weekday;
      var first = date.copyWith().add(Duration(days: week * -1 + 1));
      var format = ['yyyy', '-', 'mm', '-', 'dd'];
      var list = List.generate(
          7,
          (index) =>
              first.copyWith().add(Duration(days: index)).toDateStr(format));
      orderData.weekList = list;
      orderData.weekDay = date.weekday;
      var data = await Go().push(ByWeekFoodMenuPage(orderData));
      if (data != null) {
        viewModel.requestRefresh();
      }
    }
  }

// Future<OrderModelListData> getOrderType() async {
//   OrderModelListData item;
//   showLoadingDialog("");
//   try {
//     var data = await PostRequest.getOrderModel(1, 20);
//     if ('0' == data['code'].toString()) {
//       var list = (data['data']['rows'] as List)
//           .map((e) => OrderModelListData.fromJson(e))
//           .toList();
//       for (var type in list) {
//         if (type.orderType == 2) {
//           item = type;
//           break;
//         }
//       }
//     } else {
//       item = null;
//     }
//     hideDialog();
//   } catch (e) {
//     hideDialog();
//     item = null;
//   }
//   return item;
// }
}
